package com.systar.activity.process;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.castsoftware.java.FileExplorer;
import com.google.common.eventbus.EventBus;
import com.systar.activity.events.FileDetectionEvent;

public class ActivitySourceObserver implements Runnable
{
	private final EventBus eventBus;
	private File sourceDir;
	private FilenameFilter sourceFilter;
	private final Map<File, Long> fileToModification;

	public ActivitySourceObserver(EventBus eventBus)
	{
		this.eventBus = eventBus;
		fileToModification = new HashMap<File, Long>();
	}

	public void connect(String sourceDirPath, FilenameFilter filter) throws IOException
	{
		sourceDir = FileExplorer.getInstance().getFile(sourceDirPath);
		if (!sourceDir.isDirectory())
			throw new FileNotFoundException(sourceDirPath);

		sourceFilter = filter;
	}

	@Override
	public void run()
	{
		if (sourceDir == null)
			return;

		for (File file : sourceDir.listFiles(sourceFilter))
		{
			if (file.isHidden())
				continue;
			if (file.isDirectory())
				continue;

			long lastModified = file.lastModified();
			if (!fileToModification.containsKey(file))
			{
				// new file
				eventBus.post(new FileDetectionEvent(file));
			}
			else
			{
				long oldModified = fileToModification.get(file);
				if (oldModified != lastModified)
				{
					// updated file
					eventBus.post(new FileDetectionEvent(file));
				}
			}
			fileToModification.put(file, lastModified);
		}
	}

}
